package com.linksfield.topup.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.log4j.Logger;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @author: songgt
 * @date: 2019-03-05 14:53
 */
public class JwtUtil {

    private static Logger logger = Logger.getLogger(JwtUtil.class);

    private final static String base64Secret = "linksfieMDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY";

    /**
     * 定义泛型方法，方便传入任何类型入参对象
     */
    public static <T> String createJwt(T obj) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        //构造jwt
        JwtObj jwtObj = (JwtObj) obj;
        JwtBuilder builder = Jwts.builder().setHeaderParam("type", "jwt")
                .claim("userName", jwtObj.getUserName())
                .claim("id", jwtObj.getId())
                .claim("userPwd", jwtObj.getUserPwd())
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (jwtObj.getExpires() >= 0) {
            long expMillis = nowMillis + jwtObj.getExpires();
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }
        //生成jwt
        return builder.compact();
    }

    /**
     * 解析jwt
     *
     * @param jsonWebToken
     * @return
     */
    public static Claims parseJWT(String jsonWebToken) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(base64Secret)).parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (Exception ex) {
            logger.info("解析jwt出现异常" + ex);
            return null;
        }

    }

    public static void main(String[] args) {

        JwtObj jwtObj = new JwtObj();
        jwtObj.setUserName("admin");
        jwtObj.setUserPwd("admin");
        jwtObj.setId(1520);
        //12小时
        jwtObj.setExpires(43200000);
        String jwtStr = createJwt(jwtObj);
        System.out.println("JwtToken是：" + jwtStr);

        Claims claims = parseJWT(jwtStr);
        System.out.println(claims.get("userName") + ";" + claims.get("userPwd") + ";" + claims.get("id"));


    }

}